package main;

import java.util.*;
import models.*;
import services.MoneyService;
import voidlib.*;
/**
 * @author nevidimov
 */
public class BankController extends VoidController {

    public void listCreditsAction() {
        List<Credit> credits = new Credit().getMapper().fetchAll("bank_id = ?", VoidUser.getInstance().getId(), "status = ?", RequestStatus.Pending);
        
        this.view.put("credits", credits);
        this.initModelAndView();
    }
    
    public void changeStatusAction() {
        String id = this.request.getParameter("id");
        String status = this.request.getParameter("status");
        
        Credit credit = new Credit().getMapper().fetch(Integer.parseInt(id));
        RequestStatus newStatus = RequestStatus.Pending;
        if (status.compareTo("ok") == 0) {
            User bank = VoidUser.getInstance().getUser();
            if (MoneyService.transferMoney(credit.getBankId(), credit.getBusinessmanId(), credit.getAmount())) {
                newStatus = RequestStatus.OK;
            } else {
                newStatus = RequestStatus.Pending;
            }
        } else {
            newStatus = RequestStatus.Refused;
        }
        
        credit._status = newStatus;
        credit.save();
        
        VoidController.setMessage("Credit status set to " + newStatus.toString());
        
        this.redirect(VoidConfig.rootUrl + "bank.htm?act=listcredits");
    }
    
}
